package com.rocching.easychat.adapter;

import android.content.Context;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.rocching.easychat.R;
import com.rocching.easychat.model.GroupListModel;
import com.rocching.easychat.util.AppUtil;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;

public class GroupListAdapter extends BaseAdapter {
    private final Context context;
    private List<GroupListModel> list;

    public GroupListAdapter(Context context) {
        this.context = context;
        list = new ArrayList<>();
    }

    public void update(List<GroupListModel> list) {
        this.list = list;
        notifyDataSetChanged();
    }

    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public Object getItem(int i) {
        return list.get(i);
    }

    @Override
    public long getItemId(int i) {
        GroupListModel model = list.get(i);
        if (Objects.isNull(model)) {
            return 0;
        }
        return model.getId();
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        GroupListHolder holder = null;
        if (view == null) {
            view = LayoutInflater.from(context).inflate(R.layout.group_list_item, null);
            holder = new GroupListHolder(view);
            view.setTag(holder);
        } else {
            holder = (GroupListHolder) view.getTag();
        }
        GroupListModel model = list.get(i);
        if (!Objects.isNull(model)) {
            holder.update(model);
        }
        return view;
    }

    public static class GroupListHolder {
        private final View view;
        private final ImageView groupPhoto;
        private final TextView groupName;

        public GroupListHolder(View view) {
            this.view = view;
            groupPhoto = view.findViewById(R.id.group_photo);
            groupName = view.findViewById(R.id.group_name);
        }

        public void update(GroupListModel model) {
            groupName.setText(String.format("%s(%s)", model.getName(), model.getGroupUserCount()));
            Uri uri = AppUtil.getUserPhotoUri(model.getPhoto());
            if (uri != null) {
                Glide.with(view).load(uri).placeholder(R.drawable.loading).into(groupPhoto);
            }
        }
    }
}
